<template>
    <div class="Virtual-digital-person-box">
      <div class="Virtual3dVideo">
        <Video class="video-box" ref="AIvideo"  :SubtitlesSrc="SubtitlesSrc" :src="src"   />
        <div v-show="AIVideoLoad" class="AIVideoLoad">
          <div class="AIVideoLoad-img-box">
<!--            <img src="../../.././../assets/Load/mc.gif">-->
            <Cube3D/>
          </div>
          <div class="text-box-AI">
            {{showLoadText}}
          </div>
        </div>
      </div>
      <div class="Conversation">

<!--        <div class="Conversation-title-box">-->
<!--          <div class="Conversation-title">-->
<!--            <h2>AI虚拟数字人</h2>-->
<!--          </div>-->
<!--          <div class="Conversation-content">-->
<!--            <span>当前为您服务的AI虚拟数字人为: Andy</span>-->
<!--          </div>-->
<!--        </div>-->

        <div class="Conversation-list-box">
          <div class="message-box" v-for="(item,index) in messageList" :key="item.id"
               :class="{rightmassage: item.userId!==user.id
               ,animationClass
               ,fadeInUpBig: index+1===messageList.length
               ,animated: index+1===messageList.length
          } ">
            <div class="message-item">
              <div class="user-box">
                <div class="nickname">
                  <span>{{item.nickname}}</span>
                  <span>{{ item.creationTime}}</span>
                </div>
                <div class="img-box">
                  <img :src="item.imgUrl">
                </div>
              </div>
              <div class="content">
                <div class="content-box">
                  <span v-if="item.userId!==user.id&&index+1===messageList.length" id="contentspan">
                  </span>
                        <span v-else>
                   {{  item.conversation}}
                  </span>
                </div>

              </div>
            </div>
          </div>
        </div>
        <div class="Conversation-input-box">
          <div class="Conversation-content-box">
            <div class="Conversation-input">
              <input class="content-input" v-model="input">
            </div>
            <div class="Conversation-btn" @click="sendMessageS">
              提交
            </div>
            <div class="Conversation-Speech"
                 :style="'background: '+microphoneColor"
                 @click="SpeechClick(microphoneStatus)">
              <i class="el-icon-mic"></i>
            </div>
          </div>
          <div class="LoadAnimation" v-show="LoadShow">
            <div class="Load-box" :class="animationClass" >
              <div class="box-Load-icon">
                <i class="el-icon-loading"></i>
                <span>🚫正在飞速加载AI的大脑🧠请耐心等待，不要刷新页面，不要随便点击🚫</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <voice ref="voiceSpeech" @speechToText="speechToText"/>
    </div>
</template>

<script>
import Voice from "@/components/Speech/Voice";
var interval;
import Video from "@/components/video/Video";
import {contentTypeit} from "@/views/BlogFront/utils/plug";
import Cube3D from "@/common/Load/cube3D";
export default {
  name: "Virtual-digital-person",
  components: {Cube3D, Voice, Video},
  data() {
    return {
      SubtitlesSrc: 'https://andysama.work:8089/files/b07d639b733746b48a31fb90a722288e.ass',
      src: "https://andysama.work:8089/files/104054890204443b8d2f9720e8a6c581.webm",
      messageList :[
      ],
      animationId: "",
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")): {},
      input: '',
      rockrtClass: "",
      animationClass: "",
      LoadShow: false,
      VideoTaskInfoStatus: {},
      microphoneColor: '#4c8eee',
      microphoneStatus: true,
      AIVideoLoad: false,
      cutsceneClass: 'fadeInUpBig animated',
      showLoadText: "",
      indexText: 0,
      LoadText:[
        "虚拟人正在思考你给出的问题，请不要退出或者关闭网页，稍后我将回答你的问题",
        "小提示：视频播放完后右下角会有重新播放和下载生成对话记录的视频的按钮，可以将生成后的视频发布到博客代替你解释你的文章",
        "稍等片刻正在全速思考回答你的问题",
        "切勿关闭此页面"
      ]
    }
  },
  //计算属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    //点击语音
    SpeechClick(flag){
      console.log("状态",flag)
      switch (flag){
        case true:
          this.microphoneColor = 'greenyellow;';
          this.$refs.voiceSpeech.handleStart();
          break;
        case false:
          this.microphoneColor = '#4c8eee';
          this.$refs.voiceSpeech.handleStop();
          this.$refs.voiceSpeech.uploadRecord();
          break;
      }
      this.microphoneStatus =  !this.microphoneStatus
    },
    //语音识别后的回调
    speechToText(text){
      console.log("赋值了")
      this.input = text;
      // if(this.input!==""){
      //   // this.rockrtClass = "zoomOutUp animated";
      //   let item = {
      //     userId: this.user.id,
      //     nickname: this.user.nickname,
      //     imgUrl:  this.user.avatarUrl,
      //     conversation: text,
      //     creationTime: new Date().toLocaleString()
      //   }
      //   this.LoadShow = true;
      //   this.sendMessage(item);
      //   this.input = "";
      // }else {
      //   this.$message('😫内容为空无法发送!');
      // }
    },
    //发送信息
    sendMessage(item) {
      //加载动画
      this.AIVideoLoad = true;
      //判断是不是超过了2次对话
      if(this.messageList.length>=4){
        this.messageList = [];
      }
      //关闭下载和重新播放
      this.$refs.AIvideo.noshowControls();
      this.messageList.push(item);
      this.chatgptRes(item.conversation)
    },
    //询问chatgpt拿到返回值
    chatgptRes(conversation){
      this.request.get("/ChatAPI/chat",{
        params:{
          prompt: conversation
        }
      }).then(res=>{
        //生成视频任务
        this.Submit3DAvatarVideoText(res.choices[0].text);
        this.clearLoad();
        let  ChatGptObject={
          userId: "-1",
          nickname: "AI虚拟数字人",
          imgUrl:  require("../../../../assets/chat/Virtualhuman.png"),
          conversation: res.choices[0].text,
          creationTime: new Date().toLocaleString()
        }

        this.contentText(ChatGptObject);
        console.log("chatgpt返回的数据",ChatGptObject)
        this.messageList.push(ChatGptObject)
        // this.scrollbarBT();
        //更新到vuex
        // this.$store.state.ChatGPTMessageList= this.messageList;
      })
    },
    Submit3DAvatarVideoText(conversation){

      this.request.get("/AIAvatar/Submit3DAvatarVideoText",{
        params:{
          text: conversation
        }
      }).then(res=>{
        if( res.code === "200"){
          // this.clearLoad();
          console.log("任务id",res.data)
          //更新到vuex
          // this.$store.state.ChatGPTMessageList= this.messageList;

          //每三秒查询视频
          // this.GetVideoTaskInfo();
          this.indexText = 0;
          interval = window.setInterval(()=>{
            this.showLoadText = this.LoadText[this.indexText];
            this.GetVideoTaskInfo(res.data);
            if(this.indexText>this.LoadText.length){
              this.indexText = 0;
            }
            if(this.VideoTaskInfoStatus.status === "3"){
              this.AIVideoLoad = false;
              //调用查询生成后的视频链接
              let src = this.VideoTaskInfoStatus.taskResult.videoUrl;
              //调用子类的方法传递src
              this.$refs.AIvideo.Newload(src);
              window.clearInterval(interval);
            }
            this.indexText++;
          },3000);

        }else {
          console.log("生成视频出错")
        }

      })
    },
    GetVideoTaskInfo(taskUuid){
      //拿到提问后的src
      this.request.get("/AIAvatar/GetVideoTaskInfo",{
        params:{
          taskUuid: taskUuid
        }
      }).then(res=>{
          this.VideoTaskInfoStatus = res.data;
      })
    },
    contentText(messageItem){
      var timer = setTimeout(()=> {
        contentTypeit("#contentspan",messageItem.conversation); //打字机效果
        clearTimeout(timer);
      }, 1500);
    },
    //调用用户发送信息
    sendMessageS(){

      if(this.input!==""){
        this.rockrtClass = "zoomOutUp animated";
        let item = {
          userId: this.user.id,
          nickname: this.user.nickname,
          imgUrl:  this.user.avatarUrl,
          conversation: this.input,
          creationTime: new Date().toLocaleString()
        }
        this.LoadShow = true;
        this.sendMessage(item);
        this.input = "";
      }else {
        this.$message('😫内容为空无法发送!');
      }

    },
    scrollbarBT(){
      var ele = document.getElementById("Conversation-list-box");
      setTimeout(()=>{
        //判断元素是否出现了滚动条
        if(ele.scrollHeight > ele.clientHeight) {
          //设置滚动条到最底部
          ele.scrollTop = ele.scrollHeight;

        }
      },1000)

    },
    clearLoad(){
      this.animationClass = '';
      this.LoadShow = false;
    }
  },
  //生命周期 一 创建完成(可以访问当前this实例)
  created() {
  },
  //生命周期 一 挂载完成(可以访问DOM元素)
  mounted() {
    this.AIVideoLoad= true
    this.showLoadText = "AI虚拟人正在赶往你这里，请稍等片刻"
    setTimeout(()=>{
      this.AIVideoLoad = false;
      this.$refs.AIvideo.Toautoplay();
      this.$refs.AIvideo.toShowVideo();
    },1500)

  },
  //生命周期 - 创建之前
  beforeCreate() {
  },
  //生命周期 - 挂载之前
  beforeMount() {
  },
  //生命周期 - 更新之前
  beforeUpdate() {
  },
  //生命周期 - 更新之后
  updated() {
  },
  //生命周期 - 销毁之前
  beforeDestroy() {
  },
  //生命周期 - 销毁完成
  destroyed() {
  },
  //如果页面有keep-alive缓存功能，这个函数会触发
  activated() {
  },
}
</script>

<style lang="less" scoped>
.Virtual-digital-person-box{
  width: 100%;
  height: 100%;
  display: flex;
  .Conversation{
    width: 600px;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-around;

    .Conversation-title-box{
      flex: 0.2;
      display: flex;
      flex-direction: column;
      justify-content: space-around;

      .Conversation-title{
        h2{
          font-size: 50px;
          font-weight: 800;
          color: white;
        }
      }
      .Conversation-content{
        span{
          font-size: 20px;
          color: white;
        }
      }
    }
    .Conversation-list-box{
      z-index: 2;
      flex: 0.9;
      border-radius: 25px;
      //background: #353646;
      padding: 20px;
      display: flex;
      flex-direction: column-reverse;
      .message-box{
        width: 100%;
        display: flex;
        justify-content: flex-end ;


        .message-item{
          width: auto;
          margin-bottom: 20px;
          display: flex;
          flex-direction: column;

          .user-box{
            display: flex;
            align-items: center;
            justify-content: flex-end;
            flex-grow:0;
            .nickname{
              font-size: 15px;
              color: white;
              span{
                margin-right: 10px;
              }
            }
            .img-box{
              width: 45px;
              height: 45px;
              img{
                width: 100%;
                height: 100%;
                border-radius: 50%;
              }
            }
          }
          .content{

            margin-top: 15px;
            max-width: 1000px;
            display: flex;
            justify-content: flex-end;
            .content-box{
              display: inline-block;
              max-width: 1000px;
              padding: 15px 15px;
              background: #409eff;
              font-size: 17px;
              color: white;
              font-weight: 500;
              border-radius: 15px 1px 15px 15px;
              span{
                line-height: 25px;
                letter-spacing: 1px;
                white-space:pre-line;
                word-wrap:break-word;
              }
            }


          }
        }


      }
      .rightmassage{
        justify-content: flex-start !important;

        .message-item{
          .user-box{
            justify-content: flex-start;
            .img-box{
              order:-1;
            }
          }
          .content{
            justify-content: flex-start !important;

            .content-box{
              border-radius: 1px 15px 15px 15px !important;
              background: #393c4b !important;
            }


          }

        }
      }

    }
    .Conversation-input-box{
      z-index: 2;
      flex: 0.10;
      display: flex;
      justify-content: space-between;
      position: relative;
      .Conversation-content-box{
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: space-between;

        .Conversation-Speech{
          flex: 0.18;
          margin: 20px 20px 20px 20px;
          display: flex;
          justify-content: center;
          align-items: center;
          border-radius: 25px;
          background: #4c8eee;
          cursor: pointer;
          font-size: 30px;
          color: white;

        }


        .Conversation-input{
          flex: 0.8;
          display: flex;
          justify-content: center;
          align-items: center;
          .content-input{
            width: 100%;
            height: 60% !important;
            border-radius: 15px;
            border: 2px solid #1d90f5;
            background: rgba(66, 69, 85,0.8);
            outline:none;
            color: white;
            font-size: 20px;
            padding: 0 15px !important;
          }
          input::-webkit-input-placeholder{
            color: width;
            padding-left: 10px;
            font-size:20px;

          }
        }

        .Conversation-btn{
          flex: 0.2;
          margin: 20px 0px 20px 20px;
          display: flex;
          justify-content: center;
          align-items: center;
          border-radius: 25px;
          background: #4c8eee;
          cursor: pointer;
          font-size: 20px;
          color: white;
        }
      }


      .LoadAnimation{
        position: absolute;
        width: 100%;
        top: -5px;
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
        align-items: center;
        .Load-box{
          width: 100%;
          height: 80px;
          display: flex;
          border-radius: 40px 40px 0 0;
          background: linear-gradient(to bottom, rgba(29, 144, 245, 1), rgba(255, 255, 255, 0));
          justify-content: center;
          align-items: center;
          .box-Load-icon{
            width: 60%;
            height: 50%;
            color: white;
            display: flex;
            justify-content: center;
            align-items: center;
            span{
              margin-left: 10px;
            }
          }
        }
      }

    }

  }
  .Virtual3dVideo{
    flex: 1;
    height: 100%;
    position: relative;
    .video-box{
      position: absolute;
      z-index: 1;
    }
    .AIVideoLoad{
      z-index: 99;
      width: 100%;
      height: 100%;
      position: absolute;
      display: flex;
      justify-content: center;
      align-items: center;
      background: rgba(31, 33, 35,0.8);
      .AIVideoLoad-img-box{
        z-index: 99;
        width: 800px;
        height: 800px;
        display: flex;
        justify-content: center;
        align-items: center;
        position: relative;
        //img{
        //  width: 100%;
        //  height: 100%;
        //  opacity: 0.8;
        //}
      }


      @keyframes animate {
        17% {
          border-bottom-right-radius: 3px;
        }

        25% {
          transform: translateY(9px) rotate(22.5deg);
        }

        50% {
          transform: translateY(18px) scale(1, .9) rotate(45deg);
          border-bottom-right-radius: 40px;
        }

        75% {
          transform: translateY(9px) rotate(67.5deg);
        }

        100% {
          transform: translateY(0) rotate(90deg);
        }
      }

      @keyframes shadow {

        0%,
        100% {
          transform: scale(1, 1);
        }

        50% {
          transform: scale(1.2, 1);
        }
      }
      .text-box-AI{
        margin-top: 200px;
        font-size: 20px;
        position: absolute;
        color: white;
      }
    }
  }


}




/*base code*/
.animated {
  -webkit-animation-duration: 1s;
  animation-duration: 1s;
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
}
.animated.infinite {
  -webkit-animation-iteration-count: infinite;
  animation-iteration-count: infinite;
}
.animated.hinge {
  -webkit-animation-duration: 2s;
  animation-duration: 2s;
}
/*the animation definition*/
@-webkit-keyframes fadeInUpBig {
  0% {
    opacity: 0;
    -webkit-transform: translate3d(0, 2000px, 0);
    transform: translate3d(0, 2000px, 0)
  }
  100% {
    opacity: 1;
    -webkit-transform: none;
    transform: none
  }
}
@keyframes fadeInUpBig {
  0% {
    opacity: 0;
    -webkit-transform: translate3d(0, 2000px, 0);
    -ms-transform: translate3d(0, 2000px, 0);
    transform: translate3d(0, 2000px, 0)
  }
  100% {
    opacity: 1;
    -webkit-transform: none;
    -ms-transform: none;
    transform: none
  }
}
.fadeInUpBig {
  -webkit-animation-name: fadeInUpBig;
  animation-name: fadeInUpBig
}

</style>